<?php

namespace Auth\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Auth\Form\RegistrationForm;
//use Auth\Form\RegistrationFilter;
use Auth\Model\Auth;
use Auth\Model\UsersTable;
use Auth\Model\UsersMapper;
use Auth\Model\UsersEntity;

class RegistrationController extends AbstractActionController
{
    protected $usersTable;
    
    public function indexAction()
    {          
    	$form = new RegistrationForm('registration'); 
        $usersEntity = new UsersEntity();      
        $form->get('submit')->setValue('Register');
        $form->bind($usersEntity);
        
        $request = $this->getRequest();
        if($request->isPost())
        {     
            $form->setData($request->getPost());
            if($form->isValid())
            {                           
                $data = $form->getData();               
                /*
                $auth = new Auth();
                $auth->exchangeArray($data);               
                $this->getUserTable()->saveUser($auth);
                */            
                
                $users = $this->getUsersMapper()->saveUsers($usersEntity);
                
                if($users->getGeneratedValue())
                {
                    $this->flashMessenger()->addMessage($usersEntity->getUsrEmail());                   
                }
                return $this->redirect()->toRoute('auth/default' , array('controller' => 'registration' , 'action' => 'registration-success'));
            }
        }
        
    	return new ViewModel(
			array(
				'form' => $form ,     		
    		)
    	);
    }
    
    
    public function registrationSuccessAction()
    {
        $user_email = '';
        $flashMessenger = $this->flashMessenger();
		if ($flashMessenger->hasMessages()) {
			foreach($flashMessenger->getMessages() as $key => $value) {
                $user_email .=  $value;
			}
		}
		return new ViewModel(array('usr_email' => $user_email));
    }
    
    public function getUserTable()
    {
        if(!$this->usersTable)
        {
            $sm = $this->getServiceLocator();
            $this->usersTable = $sm->get('Auth\Model\UsersTable');
        }
        return $this->usersTable;
    }
    
    public function getUsersMapper()
    {
        $sm = $this->getServiceLocator();
        return $sm->get('UsersMapper');
    }
}